package com.quectel.cms.controller.scheduling;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceDailyDto;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceDailyTimeDto;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceDailyService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.quectel.constant.global.StatisticsConstants.TIME_RANGE_BY_MONTH;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/07/13 18:58
 */
@RestController
@RequestMapping("schedulingAttendanceDaily")
@Tag(name = "SchedulingAttendanceDailyController", description = "每日考勤记录相关api")
public class SchedulingAttendanceDailyController extends BaseController {

    @DubboReference
    private SchedulingAttendanceDailyService schedulingAttendanceDailyService;

    /**
     * 导出每日考勤加班记录
     */
    @GetMapping("exportOvertimeExcel")
    @RequirePermissions(values = "schedulingAttendanceDaily:exportExcel")
    public void exportOvertimeExcel(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        if (!params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) || !params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getRight())) {
            POIUtils.exportExcel(httpServletResponse, "每日考勤加班记录", new String[]{"考勤时间范围必传"}, Lists.newArrayList(), "每日考勤加班记录");
            return ;
        }
        Response<Object> checkResponse = checkTimeRange(TIME_RANGE_BY_MONTH, params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) + " 00:00:00"
                , params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getRight()) + " 00:00:00", 3);
        if (!checkResponse.isSuccess()) {
            POIUtils.exportExcel(httpServletResponse, "每日考勤加班记录", new String[]{checkResponse.getMessage()}, Lists.newArrayList(), "每日考勤加班记录");
            return ;
        }

        List<SchedulingAttendanceDailyDto> result = PageFetchKit.fetchAll(r -> schedulingAttendanceDailyService.queryList(r), request.getParams());
        String[] headers = new String[]{"日期", "所属小区", "工号", "姓名", "部门", "考勤组", "班制类型", "考勤状况", "加班时长(h)"};
        List<String[]> dataList = new ArrayList<>();

        for (SchedulingAttendanceDailyDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getDate()) ? DateUtils.format(data.getDate(), DateUtils.FormatType.SIMPLE) : "";
            item[1] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[2] = data.getPersonJobNo();
            item[3] = data.getPersonName();
            String deptName = "";
            if (Objects.nonNull(data.getDeptPerson()) && Objects.nonNull(data.getDeptPerson().getDept())) {
                deptName = data.getDeptPerson().getDept().getName();
            }
            item[4] = deptName;
            item[5] = Objects.nonNull(data.getSchedulingAttendanceGroup()) ? data.getSchedulingAttendanceGroup().getName() : "";
            item[6] = Objects.nonNull(data.getSchedulingAttendanceGroup()) ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.SCHEDULING_SHIFT_SYSTEM_TYPE
                    , data.getSchedulingAttendanceGroup().getShiftSystemType() + "") : "";
            item[7] = Objects.nonNull(data.getSituation()) ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.ATTENDANCE_SITUATION_TYPE, data.getSituation() + "") : "";
            item[8] = Objects.nonNull(data.getWorkOvertimeHour()) ? data.getWorkOvertimeHour().toPlainString() : "";

            dataList.add(item);
        }
        POIUtils.exportExcel(httpServletResponse, "每日考勤加班记录", headers, dataList, "每日考勤加班记录");
    }

    /**
     * 导出每日考勤记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "schedulingAttendanceDaily:exportExcel")
    public void exportParkExcel(@RequestParam Map<String, Object> params, HttpServletResponse httpServletResponse) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        if (!params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) || !params.containsKey(SystemConstants.TIME_SLOT_KEY_PAIR.getRight())) {
            POIUtils.exportExcel(httpServletResponse, "每日考勤记录", new String[]{"考勤时间范围必传"}, Lists.newArrayList(), "每日考勤记录");
            return ;
        }
        Response<Object> checkResponse = checkTimeRange(TIME_RANGE_BY_MONTH, params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getLeft()) + " 00:00:00"
                , params.get(SystemConstants.TIME_SLOT_KEY_PAIR.getRight()) + " 00:00:00", 3);
        if (!checkResponse.isSuccess()) {
            POIUtils.exportExcel(httpServletResponse, "每日考勤记录", new String[]{checkResponse.getMessage()}, Lists.newArrayList(), "每日考勤记录");
            return ;
        }

        List<SchedulingAttendanceDailyDto> result = PageFetchKit.fetchAll(r -> schedulingAttendanceDailyService.queryList(r), request.getParams());
        String[] headers = new String[]{"日期", "所属小区", "工号", "姓名", "部门", "考勤组", "班制类型", "工作时间段", "考勤状态", "应出勤时长(h)", "实际出勤时长(h)", "加班时长(h)"};
        List<String[]> dataList = new ArrayList<>();

        for (SchedulingAttendanceDailyDto data : result) {
            String[] item = new String[headers.length];
            item[0] = Objects.nonNull(data.getDate()) ? DateUtils.format(data.getDate(), DateUtils.FormatType.SIMPLE) : "";
            item[1] = Objects.nonNull(data.getVillage()) ? data.getVillage().getName() : "";
            item[2] = data.getPersonJobNo();
            item[3] = data.getPersonName();
            String deptName = "";
            if (Objects.nonNull(data.getDeptPerson()) && Objects.nonNull(data.getDeptPerson().getDept())) {
                deptName = data.getDeptPerson().getDept().getName();
            }
            item[4] = deptName;
            item[5] = Objects.nonNull(data.getSchedulingAttendanceGroup()) ? data.getSchedulingAttendanceGroup().getName() : "";
            item[6] = Objects.nonNull(data.getSchedulingAttendanceGroup()) ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.SCHEDULING_SHIFT_SYSTEM_TYPE
                    , data.getSchedulingAttendanceGroup().getShiftSystemType() + "") : "";

            StringBuilder timesBuilder = new StringBuilder();
            if (CollectionUtils.isNotEmpty(data.getTimes())) {
                for (SchedulingAttendanceDailyTimeDto time : data.getTimes()) {
                    timesBuilder.append(time.getName()).append(" (").append(DateUtils.format(time.getWorkTime(), DateUtils.FormatType.COMMON))
                            .append(" - ").append(DateUtils.format(time.getClosingTime(), DateUtils.FormatType.COMMON)).append(") , ");
                }
                timesBuilder.setCharAt(timesBuilder.length() - 1, ' ');
            }
            item[7] = timesBuilder.toString();
            item[8] = Objects.nonNull(data.getCheckStatus()) ? SysCodeUtils.easyToGetName(SysCodeKeyConstants.Attendance_Status, data.getCheckStatus() + "") : "";
            item[9] = Objects.nonNull(data.getAttendanceHour()) ? data.getAttendanceHour().toPlainString() : "";
            item[10] = Objects.nonNull(data.getRealityAttendanceHour()) ? data.getRealityAttendanceHour().toPlainString() : "";
            item[11] = Objects.nonNull(data.getWorkOvertimeHour()) ? data.getWorkOvertimeHour().toPlainString() : "";

            dataList.add(item);
        }
        POIUtils.exportExcel(httpServletResponse, "每日考勤记录", headers, dataList, "每日考勤记录");
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "schedulingAttendanceDaily:list")
    @Operation(summary = "分页获取每日考勤记录列表")
    public Response<Page<SchedulingAttendanceDailyDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = schedulingAttendanceDailyService.queryTotal(request.getParams());

        List<SchedulingAttendanceDailyDto> list = null;
        if (total > 0) {
            list = schedulingAttendanceDailyService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SchedulingAttendanceDailyDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SchedulingAttendanceDailyDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "schedulingAttendanceDaily:edit")
    @Operation(summary = "在编辑时根据id查询每日考勤记录详情")
    public Response<SchedulingAttendanceDailyDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingAttendanceDailyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingAttendanceDailyDto schedulingAttendanceDailyDto = schedulingAttendanceDailyService.selectById(id);

        return Response.<SchedulingAttendanceDailyDto>ok().wrap(schedulingAttendanceDailyDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "schedulingAttendanceDaily:info")
    @Operation(summary = "根据id查询每日考勤记录的详情")
    public Response<SchedulingAttendanceDailyDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingAttendanceDailyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingAttendanceDailyDto schedulingAttendanceDailyDto = schedulingAttendanceDailyService.selectById(id);

        return Response.<SchedulingAttendanceDailyDto>ok().wrap(schedulingAttendanceDailyDto);
    }

    /**
     * 保存
     *
     * @param schedulingAttendanceDailyDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "schedulingAttendanceDaily:edit")
    @Operation(summary = "新增每日考勤记录")
    public Response<Object> save(@RequestBody @Validated SchedulingAttendanceDailyDto schedulingAttendanceDailyDto) {

        //填充基础数据
        fillSaveCommonData(schedulingAttendanceDailyDto);

        schedulingAttendanceDailyService.save(schedulingAttendanceDailyDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param schedulingAttendanceDailyDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "schedulingAttendanceDaily:edit")
    @Operation(summary = "根据id修改每日考勤记录")
    public Response<Object> update(@RequestBody  @Validated SchedulingAttendanceDailyDto schedulingAttendanceDailyDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(schedulingAttendanceDailyDto.getId()));
        if (schedulingAttendanceDailyService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(schedulingAttendanceDailyDto);

        schedulingAttendanceDailyService.updateById(schedulingAttendanceDailyDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "schedulingAttendanceDaily:delete")
    @Operation(summary = "根据多条记录id批量删除每日考勤记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (schedulingAttendanceDailyService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        schedulingAttendanceDailyService.deleteBatch(ids);

        return Response.ok();
    }
}
